----------------------------------------------------------------------------------
-- Company: 
-- Engineer: 
-- 
-- Create Date:    18:02:37 12/25/2012 
-- Design Name: 
-- Module Name:    Gen_key - Behavioral 
-- Project Name: 
-- Target Devices: 
-- Tool versions: 
-- Description: 
--
-- Dependencies: 
--
-- Revision: 
-- Revision 0.01 - File Created
-- Additional Comments: 
--
----------------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;

-- Uncomment the following library declaration if using
-- arithmetic functions with Signed or Unsigned values
--use IEEE.NUMERIC_STD.ALL;

-- Uncomment the following library declaration if instantiating
-- any Xilinx primitives in this code.
--library UNISIM;
--use UNISIM.VComponents.all;

entity Gen_key is
    Port ( key_in : in  STD_LOGIC_VECTOR (127 downto 0);
--			  key_in_a : in  STD_LOGIC_VECTOR (127 downto 0); 
	--		  subkey_1 : out  STD_LOGIC_VECTOR (127 downto 0);-- pomocnicze wyjscie 
           subkey : out  STD_LOGIC_VECTOR (127 downto 0);
           clk : in  STD_LOGIC;
           r : in  STD_LOGIC_VECTOR(7 downto 0));
end Gen_key;

architecture Behavioral of Gen_key is
	signal b0,b1,b2,b3,rcon_temp : std_logic_vector(7 downto 0);
	signal key_temp,key_in_k : std_logic_vector (127 downto 0);
component sbox is
port (
	clk : in std_logic;
	datain : in std_logic_vector(7 downto 0);
	dataout : out std_logic_vector(7 downto 0)
);
end component;
component rcon is
    Port ( clk : in  STD_LOGIC;	
           datain : in  STD_LOGIC_VECTOR (7 downto 0);
           dataout : out  STD_LOGIC_VECTOR (7 downto 0));
end component;

begin
process (r,clk)
		begin
		key_in_k <= key_in;	
		end process;


	
	 Sbox2: sbox port map (clk=>clk, datain=>key_in_k(103 downto 96), dataout=>b3);
    Sbox1: sbox port map (clk=>clk, datain=>key_in_k(71 downto 64), dataout=>b2);
	 Sbox0: sbox port map (clk=>clk, datain=>key_in_k(39 downto 32), dataout=>b1);
	 Sbox3: sbox port map (clk=>clk, datain=>key_in_k(7 downto 0) , dataout=>b0);
	
	 Rcon1: rcon port map (clk=>clk, datain=>r,dataout=>rcon_temp);
	 
	 process (clk,r)
	 begin
	 if(rising_edge(clk))then
	 
		 key_temp(31 downto 24)<=b3 xor key_in_k(31 downto 24) xor X"00"; 
		 key_temp(63 downto 56)<=b0 xor key_in_k(63 downto 56) xor X"00"; 
		 key_temp(95 downto 88)<=b1 xor key_in_k(95 downto 88) xor X"00"; 
		 key_temp(127 downto 120)<=b2 xor key_in_k(127 downto 120) xor rcon_temp;
		 for I1 in 0 to 3 loop
		 key_temp(23+(32*I1) downto 16+(32*I1))<=key_in_k(23+(32*I1) downto 16+(32*I1))xor key_temp(31+(32*I1) downto 24+(32*I1));
		 key_temp(15+(32*I1) downto 8+(32*I1))<=key_in_k(15+(32*I1) downto 8+(32*I1))xor key_temp(23+(32*I1) downto 16+(32*I1));
		 key_temp(7+(32*I1) downto 0+(32*I1))<=key_in_k(7+(32*I1) downto 0+(32*I1))xor key_temp(15+(32*I1) downto 8+(32*I1));
		 end loop;

	 subkey<=key_temp;
end if;
end process;
	
end Behavioral;

